//公共方法集合
var ash ={
	showEditRow: function(){
		var content = $('.editrow');
		content.slideDown(500);
	},
	_datatable:{},
	initEdit:function(){
		//编辑按钮
		$(".dataEdit").each(function(){
			$(this).on("click",function(){
				$.ajax({
		            url : _ctx + "/admin/fang/project/"+$(this).attr("data"),
		            type : "get",
		            data : {},
		            dataType : "json",
		            success : function(returned) {
		            	if(returned.success){
		            		var data = returned.data;
						if(data.id)
						{
							$("#ProjectForm input[name='id']").val(data.id);
						}
						else
							$("#ProjectForm input[name='id']").val("");

						if(data.name)
						{
							$("#ProjectForm input[name='name']").val(data.name);
						}
						else
							$("#ProjectForm input[name='name']").val("");

						if(data.remark)
						{
							$("#ProjectForm textarea[name='remark']").val(data.remark);
						}
						else
							$("#ProjectForm textarea[name='remark']").val("");

						if(data.jd)
						{
							$("#ProjectForm input[name='jd']").val(data.jd);
						}
						else
							$("#ProjectForm input[name='jd']").val("");

						if(data.wd)
						{
							$("#ProjectForm input[name='wd']").val(data.wd);
						}
						else
							$("#ProjectForm input[name='wd']").val("");

						if(data.tel)
						{
							$("#ProjectForm input[name='tel']").val(data.tel);
						}
						else
							$("#ProjectForm input[name='tel']").val("");

						if(data.says)
						{
							$("#ProjectForm textarea[name='says']").val(data.says);
						}
						else
							$("#ProjectForm textarea[name='says']").val("");

						if(data.pinpaiid)
						{
							$("#ProjectForm input[name='pinpaiid']").val(data.pinpaiid);
						}
						else
							$("#ProjectForm input[name='pinpaiid']").val("");
						if(data.pinpai&&data.pinpai.name)
						{
							$("#ProjectForm input[name='pinpainame']").val(data.pinpai.name);
						}

						if(data.shengid)
						{
							$.fn.region.loadElement($("#ProjectForm select[name='shengid']"),0,data.shengid);
						}

						if(data.shiid)
						{
							$.fn.region.loadElement($("#ProjectForm select[name='shiid']"),data.shengid,data.shiid);
						}
						else
							$("#ProjectForm select[name='shiid']").val("");

						if(data.diid)
						{
							$.fn.region.loadElement($("#ProjectForm select[name='diid']"),data.shiid,data.diid);
						}
						else
							$("#ProjectForm select[name='diid']").val("");


						if(data.address)
						{
							$("#ProjectForm input[name='address']").val(data.address);
						}
						else
							$("#ProjectForm input[name='address']").val("");

						if(data.maxarea)
						{
							$("#ProjectForm input[name='maxarea']").val(data.maxarea);
						}
						else
							$("#ProjectForm input[name='maxarea']").val("");

						if(data.minarea)
						{
							$("#ProjectForm input[name='minarea']").val(data.minarea);
						}
						else
							$("#ProjectForm input[name='minarea']").val("");

						if(data.avgprice)
						{
							$("#ProjectForm input[name='avgprice']").val(data.avgprice);
						}
						else{
							$("#ProjectForm input[name='avgprice']").val("");
						}
						if(data.iscommend&&data.iscommend==1)
						{
							$("#ProjectForm input[name='iscommend']").prop("checked",true);
						}
						else{
							$("#ProjectForm input[name='iscommend']").prop("checked",false);
						}
						if(data.iskinghu&&data.iskinghu==1)
						{
							$("#ProjectForm input[name='iskinghu']").prop("checked",true);
						}
						else{
							$("#ProjectForm input[name='iskinghu']").prop("checked",false);
						}
						if(data.sortnum)
						{
							$("#ProjectForm input[name='sortnum']").val(data.avgprice);
						}
						else{
							$("#ProjectForm input[name='sortnum']").val("");
						}

						ash.showEditRow();

		            	}
		            	else{
		            		layer.msg("数据获取失败.请联系系统管理员!");
		            	}
		            	
		            },
		            erorr : function(e) {
		            	layer.msg(e.message());	
		            }
		        });
			});	
		});	
	}
};
//ztree 相關代碼
var curExpandNode=null;//临时存储打开的ztree 节点
var ztree  ={
		settings:{ 
			async : {
			        enable : true,
			        contentType : "application/json",
			        url : _ctx + "/admin/fang/pinpai/tree.json?rodom="+Math.random()*1000,
	    	},
		    data : {
		        simpleData : {
		            enable : true,
		            idKey : "id",
		            pIdKey : "pid"
		        }
	    	},
	    	view : {
	        	dblClickExpand : false,
				showIcon: function(treeId, treeNode){
					return false;
				}
				
	    	},
	    	callback : {
	    		//单一节点展开
		        beforeExpand : function(treeId, treeNode){
		        	    var pNode = curExpandNode ? curExpandNode.getParentNode() : null;
		        	    var treeNodeP = treeNode.parentTId ? treeNode.getParentNode() : null;
		        	    var zTree = $.fn.zTree.getZTreeObj("pinpaiTree");
		        	    for (var i = 0, l = !treeNodeP ? 0 : treeNodeP.children.length; i < l; i++) {
		        	        if (treeNode !== treeNodeP.children[i]) {
		        	            zTree.expandNode(treeNodeP.children[i], false);
		        	        }
		        	    }
		        	    while (pNode) {
		        	        if (pNode === treeNode) {
		        	            break;
		        	        }
		        	        pNode = pNode.getParentNode();
		        	    }
		        	    if (!pNode) {
		        	        if (treeNode === curExpandNode)
		        	            return;
		        	        if (curExpandNode && curExpandNode.open == true) {
		        	            zTree = $.fn.zTree.getZTreeObj("pinpaiTree");
		        	            if (treeNode.parentTId === curExpandNode.parentTId) {
		        	                zTree.expandNode(curExpandNode, false);
		        	            } else {
		        	                var newParents = [];
		        	                while (treeNode) {
		        	                	treeNode = treeNode.getParentNode();
		        	                    if (treeNode === curExpandNode) {
		        	                        newParents = null;
		        	                        break;
		        	                    } else if (treeNode) {
		        	                        newParents.push(treeNode);
		        	                    }
		        	                }
		        	                if (newParents != null) {
		        	                    var oldNode = curExpandNode;
		        	                    var oldParents = [];
		        	                    while (oldNode) {
		        	                        oldNode = oldNode.getParentNode();
		        	                        if (oldNode) {
		        	                            oldParents.push(oldNode);
		        	                        }
		        	                    }
		        	                    if (newParents.length > 0) {
		        	                        zTree.expandNode(oldParents[Math.abs(oldParents.length - newParents.length) - 1], false);
		        	                    } else {
		        	                        zTree.expandNode(oldParents[oldParents.length - 1], false);
		        	                    }
		        	                }
		        	            }
		        	        }
		        	        curExpandNode = treeNode;
		        	    }
		        },
		        onExpand : function(event, treeId, treeNode){
		        	curExpandNode = treeNode;
		        },
		        beforeClick : function(treeId, treeNode){
		        	
		        },
		        onClick : function(event,treeId, treeNode){
		        		/**  这是多选的代码
		        	 	var zTree = $.fn.zTree.getZTreeObj("projectTree"), nodes = zTree.getSelectedNodes(), v = "", n = "";
		        	    nodes.sort(function compare(a, b) {
		        	        return a.id - b.id;
		        	    });
		        	    for (var i = 0, l = nodes.length; i < l; i++) {
		        	        v += nodes[i].id + ",";
		        	        n += nodes[i].name + ",";
		        	    }
		        	    if (v.length > 0)
		        	        v = v.substring(0, v.length - 1);
		        	    if (n.length > 0)
		        	        n = n.substring(0, n.length - 1);
		        	    **/
		        	    var obj = $("#pinpaiid");//pid为隐藏的元素 存储获取的tree节点的id 方便提交给服务器
		        	    var objName = $("#pinpainame");
		        	    obj.val(treeNode.id);
		        	    objName.val(treeNode.name);
		        	    ztree.hide();
		        	    return false;
		        }
	    	}
	    },
	    show:function(){
	    	var obj = $("#pinpainame");//pName是触发tree的元素的id 使用时候请自行修改
	        var objset = $("#pinpainame").offset();
	        $("#pinpaiMenu").css({
	            left : objset.left + "px",
	            top : objset.top + obj.outerHeight() + "px",
	            width : obj.outerWidth() + "px"
	        }).slideDown("fast");
	        $("body").bind("mousedown", this.onBodyDown);
	    },
	    hide:function(){
	    	 $("#pinpaiMenu").fadeOut("fast");
	    	 $("body").unbind("mousedown", this.onBodyDown);
	    },
	    onBodyDown:function (event) {
	        if (!(event.target.id == "menuBtn" || event.target.id == "pinpaiMenu" || $(event.target).parents("#pinpaiMenu").length > 0)) {
	            ztree.hide();
	        }
	    }
};
//頁面加載完畢執行的方法
$(function() {

	$.fn.zTree.init($("#pinpaiTree"), ztree.settings);
	$("#pinpainame").click(function(){
		ztree.show();
	});

	
	//加载数据
	ash._datatable = $(".projectDataTable").dataTable(
					{
						language : {
							"sProcessing" : "处理中...",
							"sLengthMenu" : "显示 _MENU_ 项结果",
							"sZeroRecords" : "没有匹配结果",
							"sInfo" : "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
							"sInfoEmpty" : "显示第 0 至 0 项结果，共 0 项",
							"sInfoFiltered" : "(由 _MAX_ 项结果过滤)",
							"sInfoPostFix" : "",
							"sSearch" : "搜索:",
							"sUrl" : "",
							"sEmptyTable" : "表中数据为空",
							"sLoadingRecords" : "载入中...",
							"sInfoThousands" : ",",
							"oPaginate" : {
								"sFirst" : "首页",
								"sPrevious" : "上页",
								"sNext" : "下页",
								"sLast" : "末页"
							},
							"oAria" : {
								"sSortAscending" : ": 以升序排列此列",
								"sSortDescending" : ": 以降序排列此列"
							}
						},
						serverSide : true,
						"ajax" : _ctx + "/admin/fang/project/data.json",
						"columns" : [
								{
									"data" : "id",
									"width" : "4%",
									"render" : function(data) {
										return "<input type='checkbox' class='selectable-checkbox' name='id' data='"+data+"'>";
									}
								},
								{
									"data" : "id"
								},
								{
									"data" : "name"
								},
								{
									"data" : "imgurl"
								},
								{
									"data" : "tel"
								},
								{
									"data" : "address"
								},
								{
									"data" : "maxarea"
								},
								{
									"data" : "minarea"
								},
								{
									"data" : "avgprice"
								},
								{
									"data" : "id",
									"width" : "20%",
									"render" : function(data) {
										return "<a class='btn btn-xs btn-info dataEdit' data='"+data+"'><i class='fa fa-edit'></i>编辑</a> "+
											   "<a class='btn btn-xs btn-warning' data='"+data+"' href='"+_ctx+"/admin/fang/huxing/list?projectid="+data+"'><i class='fa fa-building-o'></i>户型</a> "+
											   "<a class='btn btn-xs btn-primary' data='"+data+"' href='"+_ctx+"/admin/fang/youhui/list?projectid="+data+"'><i class='fa fa-jpy'></i>优惠</a> "+
											   "<a class='btn btn-xs btn-danger' data='"+data+"' href='"+_ctx+"/admin/fang/libao/list?projectid="+data+"'><i class='fa fa-gift'></i>礼包</a> "+
											   "<a class='btn btn-xs btn-info' data='"+data+"' href='"+_ctx+"/admin/fang/tuce/list?projectid="+data+"'><i class='fa fa- image'></i>图册</a> ";
											   
									}
								} ],
						deferRender : true
					});
	$('.projectDataTable').on('draw.dt',function() {
		ash.initEdit();
	});
	
	//全选按钮
	$(".checkAll").on("click",function(){
		$("input:checkbox[name='id']").each(function(){
			$(this).prop("checked","checked");
		});
	});
	//反选按钮
	$(".toggleCheck").on("click",function(){
		$("input:checkbox[name='id']").each(function(){
			if($(this).prop("checked"))
				$(this).prop("checked",false);
			else
				$(this).prop("checked",true);
		});
	});
	//新增按钮
	$(".addBtn").on("click",function(){
				$(".validate input[name='id']").val("");
				$(".validate input[name='name']").val("");
				$(".validate textarea[name='remark']").val("");
				$(".validate input[name='jd']").val("");
				$(".validate input[name='wd']").val("");
				$(".validate input[name='tel']").val("");
				$(".validate textarea[name='says']").val("");
				$(".validate input[name='pinpaiid']").val("");
				$(".validate input[name='pinpainame']").val("");
				$(".validate select[name='shengid']").val("");
				$(".validate select[name='shiid']").val("");
				$(".validate select[name='diid']").val("");

				$(".validate input[name='iscommend']").prop("checked","false");
				$(".validate input[name='iskinghu']").prop("checked","false");;
				$(".validate input[name='sortnum']").val("");

				$(".validate input[name='address']").val("");
				$(".validate input[name='maxarea']").val("");
				$(".validate input[name='minarea']").val("");
				$(".validate input[name='avgprice']").val("");
				ash.showEditRow();
	});
	//删除按钮
	$(".delBtn").on("click",function(){
		 var checkedIds = "";
	        var _checked = $("input.selectable-checkbox:checked");
	        if(_checked.length==0)
	        {
	        	layer.msg("<H4><i class='fa fa-exclamation-circle'></i>警告!</H4><p>请勾选至少一条记录!</p>");
	        }
	        for (var i = 0; i < _checked.length; i++) {
	            checkedIds += $(_checked[i]).attr("data") + ",";
	        }
	        $.ajax({
	            url : _ctx + "/admin/fang/project/delete",
	            type : "post",
	            data : {
	                id : checkedIds
	            },
	            dataType : "json",
	            success : function(returned) {
	            	layer.msg("<H4><i class='fa fa-check'></i></H4><p>删除成功!</p>");
	               	ash._datatable.fnDraw(); 
	            },
	            erorr : function(e) {
	            	layer.msg(e.message());	
	            }
	        });
	});
	$(".resetAddForm").on("click",function(){
		$("#ProjectForm")[0].reset();
		$(".editrow").slideUp(500);
	})
	$(".validate").validate({
		submitHandler: function(form) {
			$.ajax({
				url:$(form).attr("action"),
				type:$(form).attr("method"),
				data:{
					id:$(".validate input[name='id']").val(),		
					name:$(".validate input[name='name']").val(),		
					imgurl:$(".validate input[name='imgurl']").val(),		
					remark:$(".validate textarea[name='remark']").val(),		
					jd:$(".validate input[name='jd']").val(),		
					wd:$(".validate input[name='wd']").val(),		
					tel:$(".validate input[name='tel']").val(),		
					says:$(".validate textarea[name='says']").val(),		
					pinpaiid:$(".validate input[name='pinpaiid']").val(),		
					shengid:$(".validate select[name='shengid']").val(),		
					shiid:$(".validate select[name='shiid']").val(),		
					diid:$(".validate select[name='diid']").val(),
					iscommend:$(".validate input[name='iscommend']").val(),
					iskinghu:$(".validate input[name='iskinghu']").val(),
					sortnum:$(".validate input[name='sortnum']").val(),
					address:$(".validate input[name='address']").val(),		
					maxarea:$(".validate input[name='maxarea']").val(),		
					minarea:$(".validate input[name='minarea']").val(),		
					avgprice:$(".validate input[name='avgprice']").val(),		
				},
				datatype:"json",
				success:function(returned){
					if(returned.success)
					{
						layer.msg(returned.msg);
					}
					else
						layer.msg(returned.msg);
					$("#ProjectForm")[0].reset();
					$(".editrow").slideUp(500);
					ash._datatable.fnDraw(); 
				},
				error:function(error){
					layer.msg(error);
				}
			})
		}
	});
});